<?php
/**
 * Created by PhpStorm.
 * User: Administrator
<<<<<<< HEAD
 * Date: 2019/2/26
 * Time: 14:11
=======
 * Date: 2019/2/25
 * Time: 18:30
>>>>>>> c80bb1fe50dcf83fa0d068a89cb583a45965e8cb
 */

namespace app\index\controller;

use think\Request;

class Gift extends Base
{
    private $giftM;

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->giftM = new \app\index\model\Gift();
    }

    /**
     * 礼物列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function giftList(){
        $key = input('get.key');
        $list = $this->giftM->where(['name|id'=>['like',"%$key%"]])->paginate(10);
        $this->assign('key', $key);
        $this->assign('data', $list);
        return $this->fetch();
    }

    /**
     * 添加礼物
     * @return false|mixed|string
     */
    public function giftAdd(){
        if (request()->isPost()){
            $data = input('param.');
            $validate = validate('Gift');
            if (!$validate->check($data)) {
                return return_api(0,$validate->getError());
            }
            try{
                $this->giftM->allowField(true)->save($data);
            }catch (\Exception $e){
                return return_api(0,$e->getMessage());
            }
            return return_api(1,'success');
        }else{
            return $this->fetch();
        }
    }

    /**
     * 修改礼物
     * @return false|mixed|string|void
     */
    public function giftEdit(){
        $data = input('param.');
        if (checkEmpty($data['id'])){
            return return_api(0,'缺少参数');
        }
        if (request()->isPost()){
            $validate = validate('Gift');
            if (!$validate->check($data)) {
                return return_api(0,$validate->getError());
            }
            try{
                $this->giftM->allowField(true)->save($data,['id'=>$data['id']]);
            }catch (\Exception $e){
                return return_api(0,$e->getMessage());
            }
            return return_api(1,'success');
        }else{
            try{
               $res = $this->giftM->where(['id'=>$data['id']])->find();
            }catch (\Exception $e){
                return $this->error('未知错误');
            }
            return $this->fetch('',[
                'data'=>$res
            ]);
        }
    }

    /**
     * 删除礼物
     * @return false|string
     */
    public function giftDel()
    {
        if (request()->isGet()) {
            $data = input('param.');
            if (checkEmpty($data['id'])) {
                return return_api(0, '缺少参数');
            }
            try {
                $this->giftM->where('id', '=', $data['id'])->delete();
            } catch (\Exception $e) {
                return return_api(0, $e->getMessage());
            }
            return return_api(1, 'success');
        } else {
            return return_api(0, '请求方式有误');
        }
    }

}